#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <signal.h>
#include </usr/include/python2.7/Python.h>

PyObject* portscan(PyObject* phost, PyObject* pstart, PyObject* pend){

    char* host = PyString_AsString(phost);
    int start = PyInt_AsLong(pstart);
    int end = PyInt_AsLong(pend);
    PyObject* pdict = PyDict_New();
    int counter = 0;


    int sock,port,value,result;

    struct sockaddr_in serv_addr;
    fd_set reads, writes;
    struct timeval timeout;

    memset(&serv_addr, 0, sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(host);
    for( port=start ; port <= end ; port++ ){
        sock = socket(PF_INET, SOCK_STREAM, 0);

        if(sock == - 1){//fputs('error', stderr);fputc('\n', stderr);
                exit(1);
            }
        
        value = fcntl(sock, F_GETFL, 0);
        fcntl(sock, F_SETFL, value | O_NONBLOCK );
        
        FD_ZERO(&reads);
        FD_SET(sock, &reads);
        writes = reads;
        
        serv_addr.sin_port = htons(port);
        connect(sock, (struct sockaddr*)&serv_addr,     sizeof(serv_addr));
           
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;
        
        result = select( sock+1, &reads, &writes, 0, &timeout);

        if( result == -1 ){//printf("select error\n");
            continue;
        }
        else if( result == 0 ){// printf("Port timeout : Port %d\n", port);
            continue;
        }
        else{
            
            if( FD_ISSET(sock, &reads) && FD_ISSET(sock, &writes) ){//  printf("Port close = %d\n", port);
                continue;
            }
            else{//printf("Port open = %d\n", port);
                PyDict_SetItem(pdict, PyInt_FromLong(port),PyInt_FromLong(counter));
                counter++;
                }
            }
        
        close(sock);
        }

    Py_INCREF(pdict);
    return pdict;
    }